package com.nosweattechnet.server;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import com.nosweattechnet.datatypes.Place;

//Runs a query on the server which searches for Places by Keyword
public class PlaceSearchAsyncTask extends CommunicatorAsyncTask {
	//Constants specified in php scripts
	private BasicNameValuePair tag=new BasicNameValuePair("tag","searchPlaces");
	private String placeNameString="place_name";
	
	//Initializes Communicator then adds tag, and then adds specified keyword with constant
	public PlaceSearchAsyncTask(String placeName) {
		super();
		super.addNameValuePair(tag);
		super.addNameValuePair(new BasicNameValuePair(placeNameString,placeName));
	}
	
	//Parses the JSONArray to an ArrayList of Places
	//IF NO JSONARRAY, I.E. NO PLACES MATCHED THE KEYWORD, THEN AN EMPTY ARRAYLIST IS RETURNED
	public ArrayList<Place> getPlaces() throws InterruptedException, ExecutionException{
		ArrayList<Place> ai=new ArrayList<Place>();
		JSONArray jarr=this.get();
		if(jarr==null){
			return ai;
		}
		for(int i=0;i<jarr.length();i++){
			try {
				ai.add(new Place(jarr.getJSONObject(i)));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return ai;
	}
}
